import json
from form import Form

class DrawerForm:

    drawer_cfg = {}
    form_cfg = {}

    def __init__(self, cfg):
        if 'drawer' not in cfg or 'form' not in cfg:
            raise Exception('package.json文件缺少drawer或form字段')

        self.drawer_cfg = cfg['drawer']
        self.form_cfg = cfg['form']

    def build_drawer_template(self, form):
        # 生成drawer组件
        tpl = f'''
        <template>
            <el-drawer title="{self.drawer_cfg['title']}" v-model="drawerVisible" width="30%">
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" label-position="right">
                    {form.generate_form_template()}
                </el-form>
                <div slot="footer" class="drawer-footer">
                    <el-button @click="drawerVisible = false">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">确 定</el-button>
                </div>
            </el-drawer>
        </template>
        '''
        return tpl

    # 初始化打开关闭drawer的函数
    def generate_drawer_functions(self, inits):
        init_functions = ''
        for func in inits:
            init_functions += f'''
            {func}();
            '''

        drawer_functions = f'''
        const emits = defineEmits(['reload'])

        const drawerVisible = ref(false)
        const openDrawer = () => {{
            drawerVisible.value = true;
            {init_functions}
        }}
        const closeDrawer = () => {{
            drawerVisible.value = false;
            // 重置表单
            ruleFormRef.value.resetFields();
        }}

        defineExpose({{
            openDrawer,
            closeDrawer
        }});
        '''
        return drawer_functions

    def display(self):
        form = Form(self.form_cfg)

        js = f'''
        <script setup>
            import {{ ref }} from 'vue'
            import {{ ElMessage }} from 'element-plus'
            {form.generate_import_code()}
            {form.generate_form_code()}
            {form.generate_submit_code()}
            {self.generate_drawer_functions(form.need_init_functions)}
        </script>
        '''
        # 生成drawer组件
        template = self.build_drawer_template(form)
        with open('src/components/Drawer.vue', 'w', encoding='utf-8') as f:
            # 写入js
            f.write(js)

            # 写入template
            f.write(template)


if __name__ == '__main__':
    with open('task/drawer.json', 'r') as f:
        cfg = json.load(f)

    drawer = DrawerForm(cfg)
    drawer.display()